//
//  JSGoodsAttributeController.m
//  jshop
//
//  Created by 张艳江 on 2019/5/16.
//  Copyright © 2019 张艳江. All rights reserved.
//

#import "SCGoodsAttributeController.h"
#import "ZLCollectionViewFlowLayout.h"
#import "SCFeatureItemCell.h"
#import "SCFeatureHeaderView.h"
#import "SCCountFooterView.h"

@interface SCGoodsAttributeController ()<UICollectionViewDelegate,UICollectionViewDataSource,ZLCollectionViewFlowLayoutDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *goodsImageView;
@property (weak, nonatomic) IBOutlet UILabel     *titleLab;
@property (weak, nonatomic) IBOutlet UILabel     *priceLab;//价格
@property (weak, nonatomic) IBOutlet UILabel     *mkPriceLab;
@property (weak, nonatomic) IBOutlet UILabel     *stockLab;//存储

@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) NSArray          *attArray;
@property (assign, nonatomic) NSInteger        maxQuantity;//库存量
@property (strong, nonatomic) NSString         *buyNum;//购买的数量
@property (strong, nonatomic) NSArray          *attNameArray;
@property (strong, nonatomic) NSString         *spec_desc;//拼接的规格

@end

@implementation SCGoodsAttributeController

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        
        ZLCollectionViewFlowLayout *flowLayout = [[ZLCollectionViewFlowLayout alloc] init];
        flowLayout.delegate = self;
        flowLayout.minimumLineSpacing = 10;
        flowLayout.minimumInteritemSpacing = 10;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(15, 96, kScreenW-30, (kScreenH - 250*kScale_H) - 96 - 50) collectionViewLayout:flowLayout];
        
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.alwaysBounceVertical = YES;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        
        //标签
        [_collectionView registerClass:[SCFeatureItemCell class] forCellWithReuseIdentifier:@"SCFeatureItemCellID"];//cell
        
        //头部
        [_collectionView registerClass:[SCFeatureHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SCFeatureHeaderViewID"];
        
        //尾部
        [_collectionView registerClass:[SCCountFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"SCCountFooterViewID"];
        
    }
    return _collectionView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];

    self.buyNum = @"1";
    self.spec_desc = @"";
    //添加数据
    [self addData];
    //设置View
    [self setupSubViews];
    
}
- (void)setupSubViews{
    
    //商品图片
    self.goodsImageView.clipsToBounds = YES;
    self.goodsImageView.contentMode = UIViewContentModeScaleAspectFill;
    ViewBorderRadius(self.goodsImageView, 5, 5, [UIColor whiteColor]);
    
    if (self.attArray.count > 0) {
        [self.view addSubview:self.collectionView];
    }else{
        SCCountFooterView *countView = [[SCCountFooterView alloc]initWithFrame:CGRectMake(15, 96, kScreenW-30, 80)];
        countView.maxValue = _maxQuantity;
        WeakSelf;
        countView.changeNumCellBlock = ^(CGFloat number) {//选择商品数量
            weakSelf.buyNum = [NSString stringWithFormat:@"%d",(int)number];
            //NSLog(@"===%@",weakSelf.buyNum);
        };
        [self.view addSubview:countView];
    }
}
#pragma mark - 表格
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.attArray.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    SCModel *model = self.attArray[section];
    return model.value.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SCFeatureItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SCFeatureItemCellID" forIndexPath:indexPath];
    SCModel *model = self.attArray[indexPath.section];
    cell.model = model.value[indexPath.row];
    
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

    SCModel *sectionModel = self.attArray[indexPath.section];
    SCModel *rowModel = sectionModel.value[indexPath.row];

    CGFloat W = [MyTool boundingRectWithString:rowModel.attr_value withHeight:25 withFont:13];
    return CGSizeMake(W+20, 25);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    SCModel *sectionModel = self.attArray[indexPath.section];
    SCModel *rowModel = sectionModel.value[indexPath.row];
    if ([rowModel.is_default intValue] == 1) {
        return;
    }else{
        for (SCModel *model in sectionModel.value) {
            if ([model.attr_v_id isEqualToString:rowModel.attr_v_id]) {
                model.is_default = @"1";
            }else{
                model.is_default = @"0";
            }
        }
    }
    [self.collectionView reloadData];
    
    NSMutableArray *spec_descArray = [NSMutableArray array];
    for (int i = 0; i < self.attNameArray.count; i++) {
        SCModel *sectionModel = self.attArray[i];
        for (SCModel *rowModel in sectionModel.value) {
            if ([rowModel.is_default intValue] == 1) {
                NSString *value = [NSString stringWithFormat:@"%@:%@",self.attNameArray[i],rowModel.attr_value];
                [spec_descArray addObject:value];
            }
        }
    }
    if (spec_descArray.count != 3) {
        return;
    }
    self.spec_desc = [[spec_descArray copy] componentsJoinedByString:@","];
    
    [self requestData];
}
#pragma mark --分区的头和尾
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{

    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        SCModel *sectionModel = self.attArray[indexPath.section];
        SCFeatureHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SCFeatureHeaderViewID" forIndexPath:indexPath];
        headerView.headerLabel.text = sectionModel.attr_name;
        return headerView;
    }else {
        SCCountFooterView *countView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"SCCountFooterViewID" forIndexPath:indexPath];
        countView.maxValue = _maxQuantity;
        WeakSelf;
        countView.changeNumCellBlock = ^(CGFloat number) {//选择商品数量
            weakSelf.buyNum = [NSString stringWithFormat:@"%d",(int)number];
            //NSLog(@"===%@",weakSelf.buyNum);
        };
        if (indexPath.section == self.attArray.count - 1) {
            return countView;
        }else{
            return nil;
        }
    }
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(kScreenW, 44);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    
    if (section == self.attArray.count - 1) {
        return CGSizeMake(kScreenW, 80);
    }
    return CGSizeMake(kScreenW, 0);
}
#pragma ZLCollectionViewFlowLayoutDelegate
//指定是什么布局，如没有指定则为BaseLayout(基础布局)
- (ZLLayoutType)collectionView:(UICollectionView *)collectionView layout:(ZLCollectionViewFlowLayout *)collectionViewLayout typeOfLayout:(NSInteger)section {
    //列布局
    return LabelLayout;
}
#pragma mark - 点击按钮
- (IBAction)clickCloseBtn:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)clickBottomBtns:(UIButton *)sender {
    
    //NSLog(@"===%@",self.spec_desc);
    if (self.spec_desc.length == 0 && self.isGiftApp != YES && self.attArray.count != 0) {
        [SVProgressHUD showImage:nil status:@"请选中购买商品的所有属性"];
        return;
    }
    if (sender.tag == 0) {//加入购物车
        [SVProgressHUD showWithStatus:@"加入中..."];
        NSDictionary *dict;
        NSString *url;
        if (self.isGiftApp == YES) {
            dict = @{@"token":Token,
                     @"gift_id":self.product_id,
                     @"num":self.buyNum};
            url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GiftCart&a=addCart"];
        }else{
            dict = @{@"token":Token,
                     @"goods_id":self.product_id,
                     @"spec_desc":self.spec_desc,
                     @"num":self.buyNum};
            url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GoodsAppCart&a=addCart"];
        }
        [[NetworkRequestTool sharedNetworkTool] POST:url parameters:dict finished:^(id result, NSString *error) {
            [SVProgressHUD showSuccessWithStatus:@"已加入购物车"];
            if (self.refreshCarNum) {
                self.refreshCarNum(@"",@"",@"");
            }
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
    }else{//立即购买
        if (self.refreshCarNum) {
            self.refreshCarNum(self.product_id,self.buyNum,self.spec_desc);
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
#pragma mark - 请求数据
- (void)requestData{
    
    NSDictionary *dict = @{@"goods_id":self.product_id,
                           @"spec_desc":self.spec_desc};
    NSString *url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GoodsApp&a=App_attr"];
    [SVProgressHUD showWithStatus:@"加载中..."];
    [[NetworkRequestTool sharedNetworkTool] POST:url parameters:dict finished:^(id result, NSString *error) {
        [SVProgressHUD dismiss];
        //NSLog(@"返回的数据%@",result);
        SCModel *model = [SCModel mj_objectWithKeyValues:result[@"data"]];
        self.product_id = model.goods_id;
        [self.goodsImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",Goods_ImageURL,model.image]] placeholderImage:[UIImage imageNamed:@""]];
        self.priceLab.text = [NSString stringWithFormat:@"¥%@",model.sku_price];
        self.stockLab.text = [NSString stringWithFormat:@"库存：%@件",model.sku_stock];
        self.maxQuantity = [model.sku_stock integerValue];
    }];
}
- (void)addData{
    
    if (self.isGiftApp == YES) {
        NSArray *images = [self.productModel.wap_pic componentsSeparatedByString:@";"];
        [self.goodsImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",Goods_ImageURL,images[0]]] placeholderImage:[UIImage imageNamed:@""]];
        self.titleLab.text = self.productModel.gift_name;
        //价格
        self.priceLab.text = [NSString stringWithFormat:@"%@ 福豆",self.productModel.payment_pure_integral];
        self.priceLab.attributedText = [MyTool setCusstomeLable:self.priceLab withTextFont:12 withRangeString:@" 福豆" withColor:RGB(230, 11, 48)];
        //库存
        self.stockLab.text = [NSString stringWithFormat:@"库存：%@件",self.productModel.sku];
        self.maxQuantity = [self.productModel.sku integerValue];
        self.mkPriceLab.text = @"";
    }else{
        [self.goodsImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",Goods_ImageURL,self.productModel.wap_pic]] placeholderImage:[UIImage imageNamed:@""]];
        self.titleLab.text = self.productModel.goods_name;
        self.priceLab.text = [NSString stringWithFormat:@"¥%@",self.productModel.goods_price];
        self.stockLab.text = [NSString stringWithFormat:@"库存：%@件",self.productModel.stock];
        self.maxQuantity = [self.productModel.stock integerValue];
        self.mkPriceLab.text = self.productModel.goods_mktprice;
        
        self.attArray = [SCModel mj_objectArrayWithKeyValuesArray:self.productModel.spec_desc];
        NSMutableArray *tempMut = [NSMutableArray array];
        for (SCModel *model in self.attArray) {
            model.value = [SCModel mj_objectArrayWithKeyValuesArray:model.value];
            [tempMut addObject:model.attr_name];
            for (SCModel *rowModel in model.value) {
                rowModel.is_default = @"0";
            }
        }
        self.attNameArray = [tempMut copy];
    }
}

@end
